package com.huika.renrench.control.more.fragment;

import java.io.File;
import java.net.URLDecoder;
import java.net.URLEncoder;

import org.json.JSONObject;

import sharesdk.cn.sharesdk.onekeyshare.MySharePopWindows;
import sharesdk.cn.sharesdk.onekeyshare.MySharePopWindows.GriViewOnImtermClick;
import sharesdk.cn.sharesdk.onekeyshare.OnekeyShareTool;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

import com.hk.app.android.lib.http.VolleyRequestManager;
import com.huika.lib.encrypt.AESCrypt;
import com.huika.lib.ui.widget.dialog.MMAlert;
import com.huika.lib.utils.StringTool;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.control.common.activity.MobileContactActivity;
import com.huika.renrench.control.common.base.BaseFra;
import com.huika.renrench.control.login.activity.LoginActivity;
import com.huika.renrench.control.more.activity.AsregardsActivity;
import com.huika.renrench.control.more.activity.FeedBackActivity;
import com.huika.renrench.support.bean.LessonDetailBean;
import com.huika.renrench.support.helps.VersionManager;
import com.huika.renrench.utils.FileTool;
import com.huika.renrench.utils.LoginUtils;
import com.huika.renrench.utils.PhoneUtil;
import com.huika.renrench.utils.PreferencesHelper;
import com.huika.renrench.utils.WebNetUtils;
import com.huika.renrench.view.MMAlertDialog;
import com.huika.renrench.view.TitleBarHelper;
import com.huika.renrench.view.webview.BBSWebViewAct;
import com.huika.renrench.view.webview.BaseWebViewAct;
import com.nostra13.universalimageloader.utils.StorageUtils;

/**
 * @author yangyuan
 * @date：2015年6月1日,
 * @describe:主页的更多Fragment
 */

// 测试ID 100714
public class MoreFragment extends BaseFra implements GriViewOnImtermClick {

	private LinearLayout making_forum_lin;
	private LinearLayout clear_cache_lin;
	private LinearLayout invite_friend_lin;
	private LinearLayout feed_back_lin;
	private LinearLayout check_update_lin;
	private LinearLayout as_regards_lin;
	private LinearLayout making_call_lin;
	private LinearLayout layoutEnvironment;

	private TextView clear_cache_text;
	private TextView more_software_update;
	private TextView making_call_text;

	private VersionManager vm;

	private MySharePopWindows popWindows;// 分享
	private LessonDetailBean detailBean;

	@Override
	protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
		View root = inflater.inflate(R.layout.frag_more, container, false);
		return root;
	}

	@Override
	protected void initWidget(View parentView) {
		super.initWidget(parentView);
		new TitleBarHelper(getActivity(), -1, -1, R.string.more_fragment);// 设置头部title

		InstantiationView(parentView);
		setOnclickListener();
	}

	private void InstantiationView(View view) {
		making_forum_lin = (LinearLayout) view.findViewById(R.id.making_forum_lin);
		clear_cache_lin = (LinearLayout) view.findViewById(R.id.clear_cache_lin);
		invite_friend_lin = (LinearLayout) view.findViewById(R.id.invite_friend_lin);
		feed_back_lin = (LinearLayout) view.findViewById(R.id.feed_back_lin);
		check_update_lin = (LinearLayout) view.findViewById(R.id.check_update_lin);
		as_regards_lin = (LinearLayout) view.findViewById(R.id.as_regards_lin);
		making_call_lin = (LinearLayout) view.findViewById(R.id.making_call_lin);
		clear_cache_text = (TextView) view.findViewById(R.id.clear_cache_text);
		more_software_update = (TextView) view.findViewById(R.id.more_software_update);
		making_call_text = (TextView) view.findViewById(R.id.making_call_text);
		layoutEnvironment = (LinearLayout) view.findViewById(R.id.layout_chang_environment);

		vm = new VersionManager(getActivity());
		initPopWindows();// 初始化分享
	}

	/** 控件添加监听器 */
	private void setOnclickListener() {
		making_forum_lin.setOnClickListener(this);
		clear_cache_lin.setOnClickListener(this);
		invite_friend_lin.setOnClickListener(this);
		feed_back_lin.setOnClickListener(this);
		check_update_lin.setOnClickListener(this);
		as_regards_lin.setOnClickListener(this);
		making_call_lin.setOnClickListener(this);
		layoutEnvironment.setOnClickListener(this);
	}

	private boolean flagCache = true;

	@Override
	public void onResume() {// 持续更新ui
		super.onResume();
		clear_cache_text.setText(FileTool.getCacheSizeString(FileTool.getCacheSize()));
		flagCache = clear_cache_text.getText().toString().length() == 0 ? false : true;
		// try {
		// more_software_update.setText("当前版本V" +
		// getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(),
		// 0).versionName);
		// }
		// catch (NameNotFoundException e) {
		// more_software_update.setText("当前版本V1.0.0");
		// e.printStackTrace();
		// }
	}

	@Override
	protected void widgetClick(View v) { 
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.making_forum_lin:// 论坛
			if (!LoginUtils.isLogin()) {
				showActivity(getActivity(), LoginActivity.class);
				return;
			}
			Intent intent = new Intent(getActivity(), BBSWebViewAct.class);
			intent.putExtra(BaseWebViewAct.PAGE_URL,getbbsUrl());
			intent.putExtra(BaseWebViewAct.PAGE_TITLE, "论坛");
			intent.putExtra(BaseWebViewAct.IS_SHOW_BOTTOM, false);
			intent.putExtra(BaseWebViewAct.IS_HELP_FEEDBACK, true);
			showActivity(getActivity(), intent);
			break;
		case R.id.clear_cache_lin:// 清空缓存
			getclear_cache();
			break;
		case R.id.invite_friend_lin:// 邀请好友
			popWindows.showPop(invite_friend_lin);
			break;
		case R.id.feed_back_lin:// 意见反馈 
			startActivity(new Intent(getActivity(), FeedBackActivity.class)); 
			break;
		case R.id.check_update_lin:// 更新
			vm.checkVersion(false, true);
			break;
		case R.id.as_regards_lin:// 关于
			startActivity(new Intent(getActivity(), AsregardsActivity.class));
			break;
		case R.id.making_call_lin:// 客服电话 
			getTel();
			break;
		case R.id.layout_chang_environment:// 切换环境
			setEnvironment();
			break;
		}
	}
	
	private String getbbsUrl() {
		long currentTime = System.currentTimeMillis() / 1000;
		String key = String.format("U1MjU1%s", String.valueOf(currentTime));
		try { 
			AESCrypt aesCrypt = new AESCrypt(key);
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("ru", GlobalApp.userModel.getAccount());//GlobalApp.userModel.getAccount()
			jsonObject.put("rp", PreferencesHelper.getString(PreferencesHelper.KEY_LOGIN_PWD));
			String code = aesCrypt.encrypt(jsonObject.toString());
			code = URLEncoder.encode(code);
			return String.format("http://bbs.renrench.com/member.php?mod=logging&action=login_register&time=%s&code=%s", String.valueOf(currentTime), code);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	private Dialog TelDialog;//

	private void getTel() {
		if (TelDialog == null) {
			TelDialog = MMAlertDialog.createPrivateDialogExitDialog(getActivity(), R.string.user_tel_phneo, R.string.user_tel, new MMAlert.DialogOnItemClickListener() {

				@Override
				public void onItemClickListener(View v, int position) {
					int id = v.getId();
					switch (id) {
					case R.id.item_second:
						PhoneUtil.TelCALL(getActivity(), making_call_text.getText().toString());
						break;
					}
				}
			});
		}
		TelDialog.show();
	}

	private Dialog cacheDialog;// 清除缓存提示对话框

	private void getclear_cache() {
		cacheDialog = MMAlertDialog.ClearcacheDate(getActivity(), getString(R.string.more_clear_cache_tips), new OnClickListener() {

			@Override
			public void onClick(View v) {
				cacheDialog.cancel();
			}
		}, new OnClickListener() {
			@Override
			public void onClick(View v) {
				File volleyCacheDir = VolleyRequestManager.getCacheDir();
				FileTool.clear(volleyCacheDir);
				File cacheDirectory = StorageUtils.getCacheDirectory(getActivity().getApplicationContext());
				FileTool.clear(cacheDirectory);
				clear_cache_text.setText(FileTool.getCacheSizeString(FileTool.getCacheSize()));
				if (flagCache) {
					showToastMsg("清空缓存成功");
					flagCache = false;
				}
			}
		});
		cacheDialog.show();
	}

	private void initPopWindows() { // ,,,
//		String[] title = new String[] { getString(R.string.wechat), getString(R.string.qq), getString(R.string.sinaweibo),getString(R.string.wechatmoments),getString(R.string.qzone) };
//		String[] platform = new String[] { Wechat.NAME, QQ.NAME, SinaWeibo.NAME ,WechatMoments.NAME,QZone.NAME};
//		Drawable[] resImg = new Drawable[] { getActivity().getResources().getDrawable(R.drawable.pm_logo_wechat), getActivity().getResources().getDrawable(R.drawable.pm_logo_qq),
//				getActivity().getResources().getDrawable(R.drawable.pm_logo_sinaweibo),getActivity().getResources().getDrawable(R.drawable.pm_logo_wechatmoments),
//				getActivity().getResources().getDrawable(R.drawable.pm_logo_qzone)};
//		popWindows = new MySharePopWindows(getActivity(), LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, title, platform, resImg, this);
	}

	String product;

	@Override
	public void onGvOnItem(String arg0) {
		product = WebNetUtils.getWebUrl("12");
		if (StringTool.isEmpty(product)) {
			return;
		}
		if (arg0.equals("短信")) {
			Intent intent = new Intent();
			intent.putExtra(MobileContactActivity.SHARE_CONTENT, String.format(MobileContactActivity.SMS_PRE, "iphone6", "13655"));
			intent.setClass(getActivity(), MobileContactActivity.class);
			getActivity().startActivity(intent);
		} else if (WechatMoments.NAME.equals(arg0)) {
			// 微信朋友圈
			ShareSDK.initSDK(getActivity());

			// TODO
			String title = "推荐人人创给你--草根创业一站式服务平台";
			String shareStr = "选项目、学技术、选址、装修、资金周转、创业交流，想创业来人人创就够了！";// 分享内容
			String img = "http://image.app.renrench.com/rrc1/M00/00/2F/CqvBj1V5TTeAY7qIAAAOCW-7Z1M076.jpg";
			// String img = "";
			OnekeyShareTool.initShareInfo(getActivity(), title, product/*
																		 * UrlConstants
																		 * .
																		 * DOWNLOAD
																		 */, shareStr/* 分享内容 */, ""/* 商品的网页地址 */, product/* 商品的网页地址 */, img, "人人创", product, R.drawable.ic_launcher,
					true, arg0, null);
		}/*
		 * else if(QQ.NAME.equals(arg0)){ //QQ好友
		 * 
		 * }
		 */else {
			ShareSDK.initSDK(getActivity());
			String title = "推荐人人创给你--草根创业一站式服务平台";
			String shareStr = "选项目、学技术、选址、装修、资金周转、创业交流，想创业来人人创就够了！";// 分享内容
			// if (shareStr.length() > 20) {
			// shareStr = shareStr.substring(0, 19);
			// }
			String img = "http://image.app.renrench.com/rrc1/M00/00/2F/CqvBj1V5TTeAY7qIAAAOCW-7Z1M076.jpg";
			// String img = "";
			String sinaUrl = "";
			if (SinaWeibo.NAME.equals(arg0)) {
				sinaUrl = product;
				if (shareStr.length()>140) {
					shareStr = shareStr.substring(0, 140);
				}
			}
			// double maxOtherPrice = 56.00;
			// shareStr = String.format(MobileContactActivity.SMS_PRE,
			// "iphone6", "13655");
			OnekeyShareTool.initShareInfo(getActivity(), title, product /*
																		 * UrlConstants
																		 * .
																		 * DOWNLOAD
																		 */, shareStr /* 分享内容 */, sinaUrl /* 商品的网页地址 */, product /* 商品的网页地址 */, img, "人人创", product,
					R.drawable.ic_launcher, true, arg0, null);
		}
	}

	private void setEnvironment() {
		final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
		alertDialog.show();
		Window window = alertDialog.getWindow();
		window.setContentView(R.layout.layot_set_environment);
		RadioGroup rg = (RadioGroup) window.findViewById(R.id.rg_environment);
		String hostFlag = PreferencesHelper.getString(PreferencesHelper.KEY_ENVIRONMENT);
		if (hostFlag.equals("test") || hostFlag.equals("")) {
			rg.check(R.id.rb_test_environment);
		} else if (hostFlag.equals("pre")) {
			rg.check(R.id.rb_pre_environment);
		} else if (hostFlag.equals("official")) {
			rg.check(R.id.rb_official_environment);
		} else if (hostFlag.equals("yangjun")) {
			rg.check(R.id.rb_yangjun_environment);
		}
		rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.rb_test_environment:// 测试
					PreferencesHelper.setString(PreferencesHelper.KEY_ENVIRONMENT, "test");
					break;
				case R.id.rb_pre_environment:// 预生产
					PreferencesHelper.setString(PreferencesHelper.KEY_ENVIRONMENT, "pre");
					break;
				case R.id.rb_official_environment:// 正式
					PreferencesHelper.setString(PreferencesHelper.KEY_ENVIRONMENT, "official");
					break;
				case R.id.rb_yangjun_environment:// 杨俊
					PreferencesHelper.setString(PreferencesHelper.KEY_ENVIRONMENT, "yangjun");
					break;
				default:
					break;
				}
				alertDialog.cancel();
				System.exit(0);
			}
		});
	}

}
